package com.ssi.myshop.ui.fragment;


import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.ssi.myshop.Presenter.IBannerPresenter;
import com.ssi.myshop.R;
import com.ssi.myshop.base.BaseFragment;
import com.ssi.myshop.bean.BannerBean;
import com.ssi.myshop.bean.FloorListBean;
import com.ssi.myshop.ui.adapter.LinearItemContentAdapter;
import com.ssi.myshop.ui.adapter.LooperPagerAdapter;
import com.ssi.myshop.ui.custom.AutoLoopViewPager;
import com.ssi.myshop.utils.LoadingUtils;
import com.ssi.myshop.utils.PresenterManager;
import com.ssi.myshop.utils.SizeUtils;
import com.ssi.myshop.view.IBannerCallBack;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends BaseFragment implements IBannerCallBack {
    private static final String TAG = "HomeFragment";
    private IBannerPresenter mBannerPresenter;
    private LooperPagerAdapter mLooperPagerAdapter;
    private LinearItemContentAdapter mLinearItemContentAdapter;

    public HomeFragment() {
        // Required empty public constructor
    }

    private Handler mHandler = new  Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:

                    break;
            }
        }
    };

    @BindView(R.id.looper_pager)
    public AutoLoopViewPager looperPager;

    @BindView(R.id.looper_point_container)
    public LinearLayout looperPointContainer;

    @BindView(R.id.home_content_list)
    RecyclerView mContentList;


    @Override
    protected int getRootViewId() {
        return R.layout.fragment_home;
    }

    @Override
    protected View lodeRootView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.base_fragment_layout, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
        looperPager.startLoop();
    }

    @Override
    public void onPause() {
        super.onPause();
        looperPager.stopLoop();
    }

    @Override
    protected void initView(View rootView) {
        mLooperPagerAdapter = new LooperPagerAdapter();
        looperPager.setAdapter(mLooperPagerAdapter);
        mLinearItemContentAdapter = new LinearItemContentAdapter();
        mContentList.setLayoutManager(new LinearLayoutManager(getContext()));

        mContentList.setAdapter(mLinearItemContentAdapter);
    }

    @Override
    protected void initPresenter() {
        mBannerPresenter = PresenterManager.getInstance().getBannerPresenter();
        mBannerPresenter.registerViewCallBack(this);
    }

    @Override
    protected void initListener() {
        looperPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (mLooperPagerAdapter.getDataSize() == 0) {
                    return;
                }
                int targetPosition = position % mLooperPagerAdapter.getDataSize();
                updateLooperIndicator(targetPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void updateLooperIndicator(int targetPosition) {
        for (int i = 0; i < looperPointContainer.getChildCount(); i++) {
            View point = looperPointContainer.getChildAt(i);
            if (i == targetPosition) {
                point.setBackgroundResource(R.drawable.shape_indacator_point_selected);
            } else {
                point.setBackgroundResource(R.drawable.shape_indacator_point_normal);
            }
        }
    }

    @Override
    protected void loadData() {
        mBannerPresenter.getBannerList();
    }

    @Override
    protected void release() {
        if (mBannerPresenter != null) {
            mBannerPresenter.unregisterViewCallBack(this);
        }
    }

    @Override
    public void getBannerSuccess(List<BannerBean> data) {
        if (data.size() > 0) {
            mLooperPagerAdapter.setData(data);
            setUpState(State.SUCCESS);
            //设置到中间点
            int dx = (Integer.MAX_VALUE / 2) % data.size();
            int targetCenterPosition = (Integer.MAX_VALUE / 2) - dx;
            looperPager.setCurrentItem(targetCenterPosition);
            looperPointContainer.removeAllViews();
            for (int i = 0; i < data.size(); i++) {
                View point = new View(getContext());
                int size = SizeUtils.dip2px(getContext(), 8);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(size, size);
                layoutParams.leftMargin = SizeUtils.dip2px(getContext(), 5);
                layoutParams.rightMargin = SizeUtils.dip2px(getContext(), 5);
                point.setLayoutParams(layoutParams);
                if (i == 0) {
                    point.setBackgroundResource(R.drawable.shape_indacator_point_selected);
                } else {
                    point.setBackgroundResource(R.drawable.shape_indacator_point_normal);
                }
                looperPointContainer.addView(point);
            }


            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://api-hmugo-web.itheima.net/api/public/v1/home/floordata")
                    .get()
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d(TAG, "onFailure: " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    FloorListBean floorListBean = new Gson().fromJson(response.body().string(), FloorListBean.class);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mLinearItemContentAdapter.setmData(floorListBean.getMessage());
                        }
                    });
                }
            });


        } else {
            setUpState(State.Empty);
        }
    }

    @Override
    public void onError(String s) {
        setUpState(State.ERROR);
    }

    @Override
    public void onLoading() {
//        LoadingUtils.loading(getContext(), "正在中....");
        setUpState(State.LOADING);
    }

    @Override
    public void onEmpty() {

    }

    @Override
    public void onSuccess() {
        LoadingUtils.dismissLoadingDialog();
    }
}
